-- Lua Battle System - 战斗管理器

local Logger = require("utils.logger")
local BattleState = require("battle.battle_state")
local CombatCalculator = require("battle.combat_calculator")
local SkillManager = require("skills.skill_manager")
local ItemManager = require("items.item_manager")
local DecisionMaker = require("ai.decision_maker")
local EventSystem = require("utils.event_system")

local BattleManager = {
    -- 战斗管理器实例
    battle_states = {}, -- 正在进行的战斗列表
    
    -- 组件实例
    combat_calculator = nil,
    skill_manager = nil,
    item_manager = nil,
    decision_maker = nil,
    event_system = nil
}

-- 战斗管理器构造函数
function BattleManager:new()
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化战斗管理器
function BattleManager:init()
    self.battle_states = {}
    self.combat_calculator = CombatCalculator:new()
    self.skill_manager = SkillManager
    self.item_manager = ItemManager
    self.decision_maker = DecisionMaker:new()
    self.event_system = EventSystem:new()

    -- 初始化技能管理器
    self.skill_manager:init()

    Logger.info("战斗管理器初始化完成")
end

-- 开始战斗
function BattleManager:start_battle(team1, team2)
    -- 创建战斗状态
    local battle_state = BattleState:new()
    battle_state:set_teams(team1, team2)
    
    -- 开始战斗
    local success = battle_state:start()
    if not success then
        Logger.error("战斗开始失败")
        return nil
    end
    
    -- 将战斗状态添加到战斗列表
    self.battle_states[battle_state.battle_id] = battle_state
    
    -- 触发战斗开始事件
    self.event_system:trigger("battle_start", battle_state.battle_id, team1, team2)
    
    Logger.info("战斗开始，战斗ID: " .. battle_state.battle_id)
    
    return battle_state.battle_id
end

-- 运行战斗回合
function BattleManager:run_turn(battle_id)
    local battle_state = self.battle_states[battle_id]
    if not battle_state then
        Logger.error("战斗不存在，战斗ID: " .. battle_id)
        return nil
    end
    
    if battle_state.battle_state ~= battle_state.states.IN_PROGRESS then
        Logger.warn("战斗未在进行中，战斗ID: " .. battle_id)
        return nil
    end
    
    -- 获取当前行动角色
    local current_character = battle_state:get_current_character()
    if not current_character then
        Logger.error("当前没有可行动的角色")
        return nil
    end
    
    Logger.info("当前行动角色: " .. current_character.name)
    
    -- 生成决策
    local decision = self:make_decision(current_character, battle_state)
    
    -- 执行决策
    local result = self:execute_decision(current_character, decision, battle_state)
    
    -- 更新战斗统计信息
    self:update_battle_stats(battle_state, result)
    
    -- 推进到下一个角色
    local next_character = battle_state:next_character()
    
    -- 检查战斗是否结束
    if battle_state.battle_state == battle_state.states.ENDED then
        -- 从战斗列表中移除
        self.battle_states[battle_id] = nil
    end
    
    return {
        battle_id = battle_id,
        current_turn = battle_state.current_turn,
        current_character = current_character,
        next_character = next_character,
        decision = decision,
        result = result,
        battle_state = battle_state:get_snapshot()
    }
end

-- 生成决策
function BattleManager:make_decision(character, battle_state)
    local decision
    
    -- 如果是玩家控制的角色，返回空决策，等待玩家输入
    if character.is_controlled then
        Logger.info(character.name .. " 是玩家控制角色，等待玩家输入")
        return nil
    else
        -- AI控制的角色，生成AI决策
        decision = self.decision_maker:generate_decisions(character, battle_state)
        decision = self.decision_maker:evaluate_decisions(character, battle_state, decision)
        decision = self.decision_maker:select_best_decision(decision)
    end
    
    return decision
end

-- 执行决策
function BattleManager:execute_decision(character, decision, battle_state)
    if not decision then
        Logger.error("决策为空，无法执行")
        return nil
    end
    
    local result = {}
    
    if decision.type == self.decision_maker.decision_types.SKILL then
        result = self:execute_skill_decision(character, decision, battle_state)
    elseif decision.type == self.decision_maker.decision_types.ITEM then
        result = self:execute_item_decision(character, decision, battle_state)
    elseif decision.type == self.decision_maker.decision_types.DEFEND then
        result = self:execute_defend_decision(character, decision, battle_state)
    elseif decision.type == self.decision_maker.decision_types.FLEE then
        result = self:execute_flee_decision(character, decision, battle_state)
    end
    
    return result
end

-- 执行技能决策
function BattleManager:execute_skill_decision(character, decision, battle_state)
    local skill = decision.skill
    local target = decision.target
    
    -- 执行技能
    local result = self.skill_manager:cast_skill(character, skill.id, target, battle_state)
    
    -- 更新战斗统计信息
    if result then
        battle_state:update_battle_stats({
            total_damage_dealt = result.damage or 0,
            total_healing_done = result.healing or 0,
            total_skills_used = 1,
            total_status_effects_applied = #(result.status_effects_applied or {})
        })
    end
    
    return result
end

-- 执行物品决策
function BattleManager:execute_item_decision(character, decision, battle_state)
    local item = decision.item
    local target = decision.target
    
    -- 执行物品使用
    local result = self.item_manager:use_item(character, item.id, target)
    
    -- 更新战斗统计信息
    if result then
        battle_state:update_battle_stats({
            total_healing_done = result.healing or 0,
            total_items_used = 1,
            total_status_effects_applied = #(result.status_effects_applied or {})
        })
    end
    
    return result
end

-- 执行防御决策
function BattleManager:execute_defend_decision(character, decision, battle_state)
    -- 执行防御
    local result = self.decision_maker:execute_defend_decision(character, decision)
    
    return result
end

-- 执行逃跑决策
function BattleManager:execute_flee_decision(character, decision, battle_state)
    -- 执行逃跑
    local result = self.decision_maker:execute_flee_decision(character, decision)
    
    if result.fled then
        -- 结束战斗，逃跑方失败
        battle_state:end_battle(character.team_id == 1 and 2 or 1, character.name .. " 成功逃跑")
    end
    
    return result
end

-- 更新战斗统计信息
function BattleManager:update_battle_stats(battle_state, result)
    if not result then
        return
    end
    
    local stats = {
        total_damage_dealt = result.damage or 0,
        total_healing_done = result.healing or 0,
        total_skills_used = result.skill_used and 1 or 0,
        total_items_used = result.item_used and 1 or 0,
        total_status_effects_applied = #(result.status_effects_applied or {})
    }
    
    battle_state:update_battle_stats(stats)
end

-- 获取战斗状态
function BattleManager:get_battle_state(battle_id)
    local battle_state = self.battle_states[battle_id]
    if not battle_state then
        Logger.error("战斗不存在，战斗ID: " .. battle_id)
        return nil
    end
    
    return battle_state:get_snapshot()
end

-- 结束战斗
function BattleManager:end_battle(battle_id, winner_team_id, reason)
    local battle_state = self.battle_states[battle_id]
    if not battle_state then
        Logger.error("战斗不存在，战斗ID: " .. battle_id)
        return false
    end
    
    local success = battle_state:end_battle(winner_team_id, reason)
    if success then
        -- 触发战斗结束事件
        self.event_system:trigger("battle_end", battle_id, winner_team_id, reason)
        
        -- 从战斗列表中移除
        self.battle_states[battle_id] = nil
    end
    
    return success
end

-- 取消战斗
function BattleManager:cancel_battle(battle_id)
    local battle_state = self.battle_states[battle_id]
    if not battle_state then
        Logger.error("战斗不存在，战斗ID: " .. battle_id)
        return false
    end
    
    -- 结束战斗
    local success = battle_state:end_battle(nil, "战斗被取消")
    if success then
        -- 从战斗列表中移除
        self.battle_states[battle_id] = nil
    end
    
    return success
end

-- 获取所有战斗状态
function BattleManager:get_all_battle_states()
    local battle_snapshots = {}
    for battle_id, battle_state in pairs(self.battle_states) do
        battle_snapshots[battle_id] = battle_state:get_snapshot()
    end
    return battle_snapshots
end

-- 导出模块
return BattleManager